package logic

import (
	"context"
	"fmt"
	"goods/crud"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateGoodStockLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateGoodStockLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateGoodStockLogic {
	return &UpdateGoodStockLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateGoodStockLogic) UpdateGoodStock(in *goods.UpdateGoodStockRequest) (*goods.UpdateGoodStockResponse, error) {
	if in.GoodID == 0 {
		return nil, fmt.Errorf("good id is required")
	}
	if in.Stock == 0 {
		return nil, nil
	}

	goodMod := crud.NewGoodsModel(crud.Client)
	info, err := goodMod.FindOne(l.ctx, in.GoodID)
	if err != nil {
		return nil, err
	}

	if info.Stock < -in.Stock && in.Stock < 0 {
		return nil, fmt.Errorf("库存不足")
	}

	err = goodMod.UpdateStock(l.ctx, in.GoodID, in.Stock)
	if err != nil {
		return nil, err
	}

	return &goods.UpdateGoodStockResponse{}, nil
}
